package com.kd.crawler.dao;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.alibaba.druid.pool.DruidDataSourceFactory;
/**
 * @author Manfred
 *
 */
public class BaseDao {
	protected static DataSource dataSource=null;
	static{
		InputStream inputStream = BaseDao.class.getClassLoader().getResourceAsStream("druid.properties");
		Properties dbProps =  new  Properties();      
		try {
			dbProps.load(inputStream);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}		
		try {
			dataSource=DruidDataSourceFactory.createDataSource(dbProps);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	public static Connection getConnection(){
		try {
			return dataSource.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	public static DataSource getDataSource(){
		return dataSource;
	}
	public <T> List<T> query(String sql,Class<T> entityClass){
		return this.query(sql, entityClass, null);
	}
	public <T> List<T> query(String sql,Class<T> entityClass,Object... params){
		QueryRunner queryRunner = new QueryRunner(dataSource); 
		try {
			return queryRunner.query(sql,  new BeanListHandler<T>(entityClass), params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}  
	}
	
	public Long getLong(String sql,Object... params){
		QueryRunner queryRunner = new QueryRunner(dataSource); 
		try {
			return (Long)queryRunner.query(sql,new ScalarHandler(1), params);
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}  
	}
	
	public int update(String sql,Object... params){
		QueryRunner runner = new QueryRunner(dataSource);  
		try {
			 return runner.update(sql, params);			
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}  
	}
	
	public Long insert(String sql,Object ...params) throws Exception {
		QueryRunner runner = new QueryRunner(dataSource);  
		try {
			int count=runner.update(sql, params);
			BigInteger bigId=( (BigInteger) runner.query("SELECT LAST_INSERT_ID()", new ScalarHandler(1))); 
			Long id=0l;
			if(bigId!=null){
				id=bigId.longValue();
			}
			if(id==null||id==0){
				return Long.valueOf(count);
			}
			return id;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}  
	}
	
	public int delete(String sql,Object ...params){
		QueryRunner runner = new QueryRunner(dataSource);  
		try {
			 return runner.update(sql, params);			
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}  
	}
	
}
